/**
 * @copyright Copyright (c) 2025 CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author Chen Yongjie
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <CUnit/Basic.h>
#include <CUnit/CUnit.h>
#include <math.h>
#include <cJSON.h>


// 测试 cJSON_GetStringValue：正常返回字符串
void test_cJSON_GetStringValue_valid(void) {
    // 正确初始化 cJSON 对象
    cJSON item = {0};
    item.type = cJSON_String;
    item.valuestring = "example";

    // 调用函数并检查返回值
    char *result = cJSON_GetStringValue(&item);
    CU_ASSERT_PTR_NOT_NULL(result);
    CU_ASSERT_STRING_EQUAL(result, "example");
}

// 测试 cJSON_GetStringValue：输入类型不为字符串
void test_cJSON_GetStringValue_invalid_type(void) {
    cJSON item = {.valuestring = "test_string", .type = 2}; // 类型为数字
    char *result = cJSON_GetStringValue(&item);
    CU_ASSERT_PTR_NULL(result);
}

// 测试 cJSON_GetStringValue：输入为 NULL
void test_cJSON_GetStringValue_null(void) {
    char *result = cJSON_GetStringValue(NULL);
    CU_ASSERT_PTR_NULL(result);
}


// 测试 cJSON_GetNumberValue：输入类型不为数字
void test_cJSON_GetNumberValue_invalid_type(void) {
    cJSON item = {.valuedouble = 123.456, .type = 1}; // 类型为字符串
    double result = cJSON_GetNumberValue(&item);
    CU_ASSERT_TRUE(isnan(result)); // 返回 NaN
}

// 测试 cJSON_GetNumberValue：输入为 NULL
void test_cJSON_GetNumberValue_null(void) {
    double result = cJSON_GetNumberValue(NULL);
    CU_ASSERT_TRUE(isnan(result)); // 返回 NaN
}

// 测试 cJSON_IsString / cJSON_IsNumber 等类型判断函数
void test_cJSON_IsType_functions(void) {
    cJSON item = {0};

    // 测试字符串
    item.type = cJSON_String;
    CU_ASSERT_TRUE(cJSON_IsString(&item));
    CU_ASSERT_FALSE(cJSON_IsNumber(&item));
    CU_ASSERT_FALSE(cJSON_IsArray(&item));

    // 测试数字
    item.type = cJSON_Number;
    CU_ASSERT_FALSE(cJSON_IsString(&item));
    CU_ASSERT_TRUE(cJSON_IsNumber(&item));
    CU_ASSERT_FALSE(cJSON_IsBool(&item));

    // 测试 true/false
    item.type = cJSON_True;
    CU_ASSERT_TRUE(cJSON_IsBool(&item));
    CU_ASSERT_TRUE(cJSON_IsTrue(&item));
    CU_ASSERT_FALSE(cJSON_IsFalse(&item));

    item.type = cJSON_False;
    CU_ASSERT_TRUE(cJSON_IsBool(&item));
    CU_ASSERT_FALSE(cJSON_IsTrue(&item));
    CU_ASSERT_TRUE(cJSON_IsFalse(&item));

    // 测试 null
    item.type = cJSON_NULL;
    CU_ASSERT_TRUE(cJSON_IsNull(&item));

    // 测试 array/object
    item.type = cJSON_Array;
    CU_ASSERT_TRUE(cJSON_IsArray(&item));
    item.type = cJSON_Object;
    CU_ASSERT_TRUE(cJSON_IsObject(&item));
}

// 测试 cJSON_CreateString / cJSON_CreateNumber
void test_cJSON_Create_functions(void) {
    cJSON *str_item = cJSON_CreateString("hello");
    CU_ASSERT_PTR_NOT_NULL(str_item);
    CU_ASSERT_TRUE(cJSON_IsString(str_item));
    CU_ASSERT_STRING_EQUAL(str_item->valuestring, "hello");
    cJSON_Delete(str_item);

    cJSON *num_item = cJSON_CreateNumber(123.456);
    CU_ASSERT_PTR_NOT_NULL(num_item);
    CU_ASSERT_TRUE(cJSON_IsNumber(num_item));
    CU_ASSERT_DOUBLE_EQUAL(num_item->valuedouble, 123.456, 1e-9);
    CU_ASSERT_EQUAL(num_item->valueint, 123);
    cJSON_Delete(num_item);

    cJSON *bool_item = cJSON_CreateBool(true);
    CU_ASSERT_PTR_NOT_NULL(bool_item);
    CU_ASSERT_TRUE(cJSON_IsTrue(bool_item));
    cJSON_Delete(bool_item);

    cJSON *null_item = cJSON_CreateNull();
    CU_ASSERT_PTR_NOT_NULL(null_item);
    CU_ASSERT_TRUE(cJSON_IsNull(null_item));
    cJSON_Delete(null_item);

    cJSON *array_item = cJSON_CreateArray();
    CU_ASSERT_PTR_NOT_NULL(array_item);
    CU_ASSERT_TRUE(cJSON_IsArray(array_item));
    cJSON_Delete(array_item);

    cJSON *obj_item = cJSON_CreateObject();
    CU_ASSERT_PTR_NOT_NULL(obj_item);
    CU_ASSERT_TRUE(cJSON_IsObject(obj_item));
    cJSON_Delete(obj_item);
}

// 测试 cJSON_Parse 和 cJSON_Print
void test_cJSON_Parse_Print(void) {
    const char *json_str = "{\"name\":\"Alice\",\"age\":30}";
    cJSON *root = cJSON_Parse(json_str);
    CU_ASSERT_PTR_NOT_NULL(root);
    CU_ASSERT_TRUE(cJSON_IsObject(root));

    cJSON *name = cJSON_GetObjectItem(root, "name");
    CU_ASSERT_PTR_NOT_NULL(name);
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(name), "Alice");

    cJSON *age = cJSON_GetObjectItem(root, "age");
    CU_ASSERT_PTR_NOT_NULL(age);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(age), 30.0, 1e-6);

    char *printed = cJSON_PrintUnformatted(root);
    CU_ASSERT_PTR_NOT_NULL(printed);
    // 允许格式差异，但关键内容应一致
    CU_ASSERT_PTR_NOT_NULL(strstr(printed, "\"name\":\"Alice\""));
    CU_ASSERT_PTR_NOT_NULL(strstr(printed, "\"age\":30"));

    cJSON_free(printed);
    cJSON_Delete(root);
}

// 测试 cJSON_GetArraySize 和 cJSON_GetArrayItem
void test_cJSON_Array_functions(void) {
    const char *json_arr = "[1, 2, 3, 4]";
    cJSON *arr = cJSON_Parse(json_arr);
    CU_ASSERT_PTR_NOT_NULL(arr);
    CU_ASSERT_TRUE(cJSON_IsArray(arr));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 4);

    cJSON *item0 = cJSON_GetArrayItem(arr, 0);
    CU_ASSERT_PTR_NOT_NULL(item0);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(item0), 1.0, 1e-9);

    cJSON *item3 = cJSON_GetArrayItem(arr, 3);
    CU_ASSERT_PTR_NOT_NULL(item3);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(item3), 4.0, 1e-9);

    // 越界访问
    CU_ASSERT_PTR_NULL(cJSON_GetArrayItem(arr, 5));
    CU_ASSERT_PTR_NULL(cJSON_GetArrayItem(arr, -1));

    cJSON_Delete(arr);
}

// 测试 cJSON_AddItemToObject 和 cJSON_AddItemToArray
void test_cJSON_AddItem_functions(void) {
    cJSON *obj = cJSON_CreateObject();
    cJSON *arr = cJSON_CreateArray();

    cJSON *str_val = cJSON_CreateString("test");
    cJSON *num_val = cJSON_CreateNumber(42.0);

    CU_ASSERT_TRUE(cJSON_AddItemToObject(obj, "key1", str_val));
    CU_ASSERT_TRUE(cJSON_AddItemToArray(arr, num_val));

    // 验证添加成功
    cJSON *retrieved = cJSON_GetObjectItem(obj, "key1");
    CU_ASSERT_PTR_NOT_NULL(retrieved);
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(retrieved), "test");

    retrieved = cJSON_GetArrayItem(arr, 0);
    CU_ASSERT_PTR_NOT_NULL(retrieved);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(retrieved), 42.0, 1e-9);

    cJSON_Delete(obj);
    cJSON_Delete(arr);
}

// 测试 cJSON_Duplicate (深拷贝)
void test_cJSON_Duplicate(void) {
    cJSON *original = cJSON_CreateObject();
    cJSON_AddStringToObject(original, "msg", "hello");
    cJSON_AddNumberToObject(original, "count", 100);

    cJSON *copy = cJSON_Duplicate(original, true);
    CU_ASSERT_PTR_NOT_NULL(copy);
    CU_ASSERT_TRUE(cJSON_Compare(original, copy, false));

    // 修改原对象，copy 应不受影响（但这里只验证结构一致）
    cJSON *msg_copy = cJSON_GetObjectItem(copy, "msg");
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(msg_copy), "hello");

    cJSON_Delete(original);
    cJSON_Delete(copy);
}

// 测试 cJSON_Compare
void test_cJSON_Compare(void) {
    cJSON *a = cJSON_CreateNumber(3.14);
    cJSON *b = cJSON_CreateNumber(3.14);
    cJSON *c = cJSON_CreateNumber(2.71);

    CU_ASSERT_TRUE(cJSON_Compare(a, b, false));
    CU_ASSERT_FALSE(cJSON_Compare(a, c, false));

    cJSON_Delete(a);
    cJSON_Delete(b);
    cJSON_Delete(c);

    // 对象比较
    cJSON *obj1 = cJSON_Parse("{\"x\":1,\"y\":2}");
    cJSON *obj2 = cJSON_Parse("{\"y\":2,\"x\":1}"); // 顺序不同但内容相同
    CU_ASSERT_PTR_NOT_NULL(obj1);
    CU_ASSERT_PTR_NOT_NULL(obj2);
    CU_ASSERT_TRUE(cJSON_Compare(obj1, obj2, false));

    cJSON_Delete(obj1);
    cJSON_Delete(obj2);
}

// 测试 cJSON_HasObjectItem
void test_cJSON_HasObjectItem(void) {
    const char *json = "{\"name\":\"Alice\",\"age\":30}";
    cJSON *obj = cJSON_Parse(json);
    CU_ASSERT_PTR_NOT_NULL(obj);
    CU_ASSERT_TRUE(cJSON_HasObjectItem(obj, "name"));
    CU_ASSERT_TRUE(cJSON_HasObjectItem(obj, "age"));
    CU_ASSERT_FALSE(cJSON_HasObjectItem(obj, "missing"));
    CU_ASSERT_FALSE(cJSON_HasObjectItem(NULL, "name"));
    cJSON_Delete(obj);
}

// 测试空数组和空对象的 GetArraySize / GetObjectItem
void test_cJSON_EmptyArrayObject(void) {
    cJSON *arr = cJSON_CreateArray();
    CU_ASSERT_PTR_NOT_NULL(arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 0);
    CU_ASSERT_PTR_NULL(cJSON_GetArrayItem(arr, 0));
    CU_ASSERT_PTR_NULL(cJSON_GetArrayItem(arr, -1));
    cJSON_Delete(arr);

    cJSON *obj = cJSON_CreateObject();
    CU_ASSERT_PTR_NOT_NULL(obj);
    CU_ASSERT_PTR_NULL(cJSON_GetObjectItem(obj, "any"));
    CU_ASSERT_PTR_NULL(cJSON_GetObjectItemCaseSensitive(obj, "Any"));
    cJSON_Delete(obj);
}

// 测试 cJSON_DetachItemFromArray 和 cJSON_DeleteItemFromArray
void test_cJSON_DetachDeleteArray(void) {
    cJSON *arr = cJSON_Parse("[1, 2, 3]");
    CU_ASSERT_PTR_NOT_NULL(arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 3);

    cJSON *item1 = cJSON_DetachItemFromArray(arr, 1);
    CU_ASSERT_PTR_NOT_NULL(item1);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(item1), 2.0, 1e-9);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 2);

    cJSON_Delete(item1);

    cJSON_DeleteItemFromArray(arr, 0);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 1);
    cJSON *remain = cJSON_GetArrayItem(arr, 0);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(remain), 3.0, 1e-9);

    cJSON_Delete(arr);
}

// 测试 cJSON_CreateIntArray / CreateStringArray 等辅助构造函数
void test_cJSON_CreateArrayHelpers(void) {
    int nums[] = {10, 20, 30};
    cJSON *int_arr = cJSON_CreateIntArray(nums, 3);
    CU_ASSERT_PTR_NOT_NULL(int_arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(int_arr), 3);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(int_arr, 1)), 20.0, 1e-9);
    cJSON_Delete(int_arr);

    const char *strs[] = {"a", "b", "c"};
    cJSON *str_arr = cJSON_CreateStringArray(strs, 3);
    CU_ASSERT_PTR_NOT_NULL(str_arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(str_arr), 3);
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(cJSON_GetArrayItem(str_arr, 2)), "c");
    cJSON_Delete(str_arr);

    double doubles[] = {1.1, 2.2, 3.3};
    cJSON *dbl_arr = cJSON_CreateDoubleArray(doubles, 3);
    CU_ASSERT_PTR_NOT_NULL(dbl_arr);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(dbl_arr, 0)), 1.1, 1e-9);
    cJSON_Delete(dbl_arr);
}

// 测试 cJSON_Minify
void test_cJSON_Minify(void) {
    char json_with_spaces[] = " { \"a\" : 1 , \"b\" : [ 2 , 3 ] } ";
    char expected[] = "{\"a\":1,\"b\":[2,3]}";
    cJSON_Minify(json_with_spaces);
    CU_ASSERT_STRING_EQUAL(json_with_spaces, expected);

    char json_with_comments[] = "{\n// comment\n\"key\": \"value\"/* another */\n}";
    char expected2[] = "{\"key\":\"value\"}";
    cJSON_Minify(json_with_comments);
    CU_ASSERT_STRING_EQUAL(json_with_comments, expected2);
}

// 测试 cJSON_SetValuestring
void test_cJSON_SetValuestring(void) {
    cJSON *str_item = cJSON_CreateString("original");
    CU_ASSERT_PTR_NOT_NULL(str_item);

    char *new_str = cJSON_SetValuestring(str_item, "updated");
    CU_ASSERT_PTR_NOT_NULL(new_str);
    CU_ASSERT_STRING_EQUAL(new_str, "updated");
    CU_ASSERT_STRING_EQUAL(str_item->valuestring, "updated");

    // 测试缩短字符串（原 buffer 足够）
    new_str = cJSON_SetValuestring(str_item, "hi");
    CU_ASSERT_PTR_NOT_NULL(new_str);
    CU_ASSERT_STRING_EQUAL(new_str, "hi");

    // 测试非字符串类型或引用类型返回 NULL
    cJSON *num = cJSON_CreateNumber(123);
    CU_ASSERT_PTR_NULL(cJSON_SetValuestring(num, "test"));
    cJSON_Delete(num);

    cJSON_Delete(str_item);
}

// 测试 cJSON_Parse 错误处理
void test_cJSON_Parse_invalid(void) {
    CU_ASSERT_PTR_NULL(cJSON_Parse(NULL));
    CU_ASSERT_PTR_NULL(cJSON_Parse(""));
    CU_ASSERT_PTR_NULL(cJSON_Parse("{"));
    CU_ASSERT_PTR_NULL(cJSON_Parse("[1, 2"));
    CU_ASSERT_PTR_NULL(cJSON_Parse("invalid"));

    // 检查错误指针位置（可选，基础测试）
    cJSON_Parse("{ \"a\": ");
    const char *err = cJSON_GetErrorPtr();
    CU_ASSERT_PTR_NOT_NULL(err);
}

// 测试 cJSON_Compare 深度嵌套结构
void test_cJSON_Compare_nested(void) {
    const char *json1 = "{\"a\":[1,2],\"b\":{\"x\":true}}";
    const char *json2 = "{\"b\":{\"x\":true},\"a\":[1,2]}"; // 顺序不同
    cJSON *obj1 = cJSON_Parse(json1);
    cJSON *obj2 = cJSON_Parse(json2);
    CU_ASSERT_PTR_NOT_NULL(obj1);
    CU_ASSERT_PTR_NOT_NULL(obj2);
    CU_ASSERT_TRUE(cJSON_Compare(obj1, obj2, false));

    // 数组顺序不同应不等
    cJSON *arr1 = cJSON_Parse("[1,2]");
    cJSON *arr2 = cJSON_Parse("[2,1]");
    CU_ASSERT_FALSE(cJSON_Compare(arr1, arr2, false));

    cJSON_Delete(obj1);
    cJSON_Delete(obj2);
    cJSON_Delete(arr1);
    cJSON_Delete(arr2);
}

// 测试 cJSON_GetObjectItemCaseSensitive
void test_cJSON_GetObjectItemCaseSensitive(void) {
    const char *json = "{\"Name\":\"Alice\",\"NAME\":\"BOB\"}";
    cJSON *obj = cJSON_Parse(json);
    CU_ASSERT_PTR_NOT_NULL(obj);

    cJSON *item1 = cJSON_GetObjectItemCaseSensitive(obj, "Name");
    CU_ASSERT_PTR_NOT_NULL(item1);
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(item1), "Alice");

    cJSON *item2 = cJSON_GetObjectItemCaseSensitive(obj, "name");
    CU_ASSERT_PTR_NULL(item2);

    cJSON_Delete(obj);
}


// 测试 cJSON_IsXXX 函数对 NULL 输入的处理（应返回 false）
void test_cJSON_IsType_null_input(void) {
    CU_ASSERT_FALSE(cJSON_IsInvalid(NULL));
    CU_ASSERT_FALSE(cJSON_IsFalse(NULL));
    CU_ASSERT_FALSE(cJSON_IsTrue(NULL));
    CU_ASSERT_FALSE(cJSON_IsBool(NULL));
    CU_ASSERT_FALSE(cJSON_IsNull(NULL));
    CU_ASSERT_FALSE(cJSON_IsNumber(NULL));
    CU_ASSERT_FALSE(cJSON_IsString(NULL));
    CU_ASSERT_FALSE(cJSON_IsArray(NULL));
    CU_ASSERT_FALSE(cJSON_IsObject(NULL));
    CU_ASSERT_FALSE(cJSON_IsRaw(NULL));
}

// 测试 cJSON_GetArraySize / cJSON_GetArrayItem 对非数组类型输入
void test_cJSON_Array_functions_invalid_type(void) {
    cJSON item = {0};
    item.type = cJSON_String;
    item.valuestring = "not_array";

    CU_ASSERT_EQUAL(cJSON_GetArraySize(&item), 0);
    CU_ASSERT_PTR_NULL(cJSON_GetArrayItem(&item, 0));
}

// 测试 cJSON_GetObjectItem 对非对象类型输入
void test_cJSON_GetObjectItem_invalid_type(void) {
    cJSON item = {0};
    item.type = cJSON_Number;
    item.valuedouble = 42.0;

    CU_ASSERT_PTR_NULL(cJSON_GetObjectItem(&item, "key"));
    CU_ASSERT_PTR_NULL(cJSON_GetObjectItemCaseSensitive(&item, "KEY"));
    CU_ASSERT_FALSE(cJSON_HasObjectItem(&item, "key"));
}

// 测试 cJSON_AddItemToObject / cJSON_AddItemToArray 的健壮性（NULL 输入）
void test_cJSON_AddItem_null_inputs(void) {
    CU_ASSERT_FALSE(cJSON_AddItemToObject(NULL, "key", cJSON_CreateString("val")));
    CU_ASSERT_FALSE(cJSON_AddItemToObject(cJSON_CreateObject(), NULL, cJSON_CreateString("val")));
    CU_ASSERT_FALSE(cJSON_AddItemToObject(cJSON_CreateObject(), "key", NULL));

    CU_ASSERT_FALSE(cJSON_AddItemToArray(NULL, cJSON_CreateString("val")));
    CU_ASSERT_FALSE(cJSON_AddItemToArray(cJSON_CreateArray(), NULL));
}

// 测试 cJSON_Duplicate 深拷贝后字符串独立性
void test_cJSON_Duplicate_string_independence(void) {
    cJSON *original = cJSON_CreateString("original_value");
    CU_ASSERT_PTR_NOT_NULL(original);

    cJSON *copy = cJSON_Duplicate(original, true);
    CU_ASSERT_PTR_NOT_NULL(copy);
    CU_ASSERT_STRING_EQUAL(copy->valuestring, "original_value");

    // 修改原字符串（通过 cJSON_SetValuestring）
    char *new_str = cJSON_SetValuestring(original, "modified");
    CU_ASSERT_STRING_EQUAL(new_str, "modified");
    CU_ASSERT_STRING_EQUAL(copy->valuestring, "original_value"); // 副本不应改变

    cJSON_Delete(original);
    cJSON_Delete(copy);
}

// 测试 cJSON_Print / cJSON_PrintUnformatted 对 NULL 输入
void test_cJSON_Print_null_input(void) {
    CU_ASSERT_PTR_NULL(cJSON_Print(NULL));
    CU_ASSERT_PTR_NULL(cJSON_PrintUnformatted(NULL));
}

// 测试 cJSON_Minify 对 NULL 和空串输入
void test_cJSON_Minify_edge_cases(void) {
    // NULL 输入
    cJSON_Minify(NULL); // 应安全返回，无崩溃

    // 空字符串
    char empty[] = "";
    cJSON_Minify(empty);
    CU_ASSERT_STRING_EQUAL(empty, "");

    // 仅空白
    char whites[] = "   \t\n\r  ";
    cJSON_Minify(whites);
    CU_ASSERT_STRING_EQUAL(whites, "");
}

// 测试 cJSON_CreateStringReference 和 CreateObjectReference
void test_cJSON_CreateReference_types(void) {
    const char *literal = "referenced_string";
    cJSON *str_ref = cJSON_CreateStringReference(literal);
    CU_ASSERT_PTR_NOT_NULL(str_ref);
    CU_ASSERT_TRUE(str_ref->type & cJSON_IsReference);
    CU_ASSERT_STRING_EQUAL(str_ref->valuestring, literal);
    cJSON_Delete(str_ref); // 不应 free literal

    cJSON *obj_inner = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj_inner, "x", 100);
    cJSON *obj_ref = cJSON_CreateObjectReference(obj_inner);
    CU_ASSERT_PTR_NOT_NULL(obj_ref);
    CU_ASSERT_TRUE(obj_ref->type & cJSON_IsReference);
    CU_ASSERT_PTR_EQUAL(obj_ref->child, obj_inner);
    CU_ASSERT_TRUE(cJSON_IsObject(obj_ref));
    cJSON_Delete(obj_ref); // 不应 delete obj_inner
    cJSON_Delete(obj_inner);
}

// 测试 cJSON_SetNumberHelper 返回值与内部状态一致性
void test_cJSON_SetNumberHelper(void) {
    cJSON *item = cJSON_CreateNumber(0.0);
    CU_ASSERT_PTR_NOT_NULL(item);

    double result = cJSON_SetNumberHelper(item, 123.456);
    CU_ASSERT_DOUBLE_EQUAL(result, 123.456, 1e-9);
    CU_ASSERT_DOUBLE_EQUAL(item->valuedouble, 123.456, 1e-9);
    CU_ASSERT_EQUAL(item->valueint, 123);

    // 测试 INT_MAX 溢出
    result = cJSON_SetNumberHelper(item, (double)INT_MAX + 1000.0);
    CU_ASSERT_EQUAL(item->valueint, INT_MAX);
    CU_ASSERT_DOUBLE_EQUAL(result, (double)INT_MAX + 1000.0, 1e-6); // valuedouble 仍保留原始值

    cJSON_Delete(item);
}

// 测试 cJSON_DetachItemViaPointer 的各种位置（首、中、尾）
void test_cJSON_DetachItemViaPointer(void) {
    cJSON *arr = cJSON_Parse("[1, 2, 3]");
    CU_ASSERT_PTR_NOT_NULL(arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 3);

    cJSON *middle = cJSON_GetArrayItem(arr, 1);
    CU_ASSERT_PTR_NOT_NULL(middle);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(middle), 2.0, 1e-9);

    cJSON *detached = cJSON_DetachItemViaPointer(arr, middle);
    CU_ASSERT_PTR_EQUAL(detached, middle);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 2);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(arr, 0)), 1.0, 1e-9);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(arr, 1)), 3.0, 1e-9);

    cJSON_Delete(detached);
    cJSON_Delete(arr);
}

// 测试 cJSON_InsertItemInArray：插入到开头、中间、末尾、越界
void test_cJSON_InsertItemInArray(void) {
    cJSON *arr = cJSON_CreateArray();
    cJSON_AddItemToArray(arr, cJSON_CreateNumber(2));
    cJSON_AddItemToArray(arr, cJSON_CreateNumber(3)); // [2, 3]

    // 插入到开头 (index=0)
    CU_ASSERT_TRUE(cJSON_InsertItemInArray(arr, 0, cJSON_CreateNumber(1)));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 3);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(arr, 0)), 1.0, 1e-9);

    // 插入到中间 (index=2)
    CU_ASSERT_TRUE(cJSON_InsertItemInArray(arr, 2, cJSON_CreateNumber(2.5)));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 4);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(arr, 2)), 2.5, 1e-9);

    // 插入到末尾 (index=4，超出当前 size，应追加)
    CU_ASSERT_TRUE(cJSON_InsertItemInArray(arr, 4, cJSON_CreateNumber(4)));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 5);
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetArrayItem(arr, 4)), 4.0, 1e-9);

    cJSON_Delete(arr);
}

// 测试 cJSON_ReplaceItemInArray 和 cJSON_ReplaceItemInObject
void test_cJSON_ReplaceItem(void) {
    // Replace in array
    cJSON *arr = cJSON_Parse("[10, 20, 30]");
    cJSON *new_item = cJSON_CreateString("replaced");
    CU_ASSERT_TRUE(cJSON_ReplaceItemInArray(arr, 1, new_item));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 3);
    cJSON *item = cJSON_GetArrayItem(arr, 1);
    CU_ASSERT_TRUE(cJSON_IsString(item));
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(item), "replaced");

    // Replace in object
    cJSON *obj = cJSON_Parse("{\"a\":1,\"b\":2}");
    new_item = cJSON_CreateBool(true);
    CU_ASSERT_TRUE(cJSON_ReplaceItemInObject(obj, "b", new_item));
    cJSON *b_val = cJSON_GetObjectItem(obj, "b");
    CU_ASSERT_TRUE(cJSON_IsTrue(b_val));

    cJSON_Delete(arr);
    cJSON_Delete(obj);
}

// 测试 cJSON_GetArraySize 对非数组类型/NULL 的安全行为
void test_cJSON_GetArraySize_safety(void) {
    CU_ASSERT_EQUAL(cJSON_GetArraySize(NULL), 0);

    cJSON str_item = {0};
    str_item.type = cJSON_String;
    str_item.valuestring = "not_array";
    CU_ASSERT_EQUAL(cJSON_GetArraySize(&str_item), 0);

    cJSON num_item = {0};
    num_item.type = cJSON_Number;
    num_item.valuedouble = 42.0;
    CU_ASSERT_EQUAL(cJSON_GetArraySize(&num_item), 0);
}

// 测试 cJSON_Compare 对 Raw、null、bool 的精确性
void test_cJSON_Compare_exact_types(void) {
    // null vs null
    cJSON *a = cJSON_CreateNull();
    cJSON *b = cJSON_CreateNull();
    CU_ASSERT_TRUE(cJSON_Compare(a, b, false));
    cJSON_Delete(a); cJSON_Delete(b);

    // true vs true, false vs false
    a = cJSON_CreateTrue();
    b = cJSON_CreateTrue();
    CU_ASSERT_TRUE(cJSON_Compare(a, b, false));
    cJSON_Delete(a); cJSON_Delete(b);

    a = cJSON_CreateFalse();
    b = cJSON_CreateFalse();
    CU_ASSERT_TRUE(cJSON_Compare(a, b, false));
    cJSON_Delete(a); cJSON_Delete(b);

    // Raw compare
    a = cJSON_CreateRaw("{\"x\":1}");
    b = cJSON_CreateRaw("{\"x\":1}");
    CU_ASSERT_TRUE(cJSON_Compare(a, b, false));
    cJSON_Delete(a); cJSON_Delete(b);

    a = cJSON_CreateRaw("{\"x\":1}");
    b = cJSON_CreateRaw("{\"x\":2}");
    CU_ASSERT_FALSE(cJSON_Compare(a, b, false));
    cJSON_Delete(a); cJSON_Delete(b);
}

// 测试 cJSON_ParseWithLength 支持非 null-terminated buffer
void test_cJSON_ParseWithLength_non_null_terminated(void) {
    char buffer[] = "{ \"valid\": true } extra garbage";
    // 只解析前 17 字节，不含 "extra garbage"
    cJSON *obj = cJSON_ParseWithLength(buffer, 17);
    CU_ASSERT_PTR_NOT_NULL(obj);
    CU_ASSERT_TRUE(cJSON_IsObject(obj));
    CU_ASSERT_TRUE(cJSON_IsTrue(cJSON_GetObjectItem(obj, "valid")));
    cJSON_Delete(obj);

    // 验证 Parse 默认要求 null-terminated（应失败）
    CU_ASSERT_PTR_NULL(cJSON_Parse(buffer)); // 因为后面有 garbage 且无 \0 结束
}

// 测试 cJSON_malloc / cJSON_free 可通过钩子替换（简单验证）
void test_cJSON_malloc_free_hooks(void) {
    int malloc_called = 0, free_called = 0;
    void *my_malloc(size_t sz) {
        malloc_called++;
        return malloc(sz);
    }
    void my_free(void *p) {
        if (p) free_called++;
        free(p);
    }

    cJSON_Hooks hooks = {my_malloc, my_free};
    cJSON_InitHooks(&hooks);

    cJSON *item = cJSON_CreateString("test");
    CU_ASSERT_PTR_NOT_NULL(item);
    CU_ASSERT_TRUE(malloc_called > 0);
    int before_free = free_called;
    cJSON_Delete(item);
    CU_ASSERT_TRUE(free_called > before_free);

    // 恢复默认钩子
    cJSON_InitHooks(NULL);
}

// 测试 cJSON_AddItemReferenceToArray / ToObject：确保是引用而非深拷贝
void test_cJSON_AddItemReference(void) {
    cJSON *arr = cJSON_CreateArray();
    cJSON *obj = cJSON_CreateObject();

    cJSON *orig_str = cJSON_CreateString("referenced");
    CU_ASSERT_TRUE(cJSON_AddItemReferenceToArray(arr, orig_str));
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 1);
    cJSON *ref_item = cJSON_GetArrayItem(arr, 0);
    CU_ASSERT_PTR_EQUAL(ref_item->valuestring, orig_str->valuestring); // 同一指针
    CU_ASSERT_TRUE(ref_item->type & cJSON_IsReference);

    CU_ASSERT_TRUE(cJSON_AddItemReferenceToObject(obj, "key", orig_str));
    cJSON *ref_obj_item = cJSON_GetObjectItem(obj, "key");
    CU_ASSERT_PTR_EQUAL(ref_obj_item->valuestring, orig_str->valuestring);
    CU_ASSERT_TRUE(ref_obj_item->type & cJSON_IsReference);

    cJSON_Delete(arr);
    cJSON_Delete(obj);
    // orig_str 仍有效，不应被释放
    CU_ASSERT_STRING_EQUAL(orig_str->valuestring, "referenced");
    cJSON_Delete(orig_str); // 此时才真正释放
}

// 测试 cJSON_CreateStringReference 删除时不会释放原始字符串字面量
void test_cJSON_CreateStringReference_no_free_literal(void) {
    // 使用字符串字面量（不可 free）
    const char *literal = "do_not_free_me";
    cJSON *ref = cJSON_CreateStringReference(literal);
    CU_ASSERT_PTR_NOT_NULL(ref);
    CU_ASSERT_TRUE(ref->type & cJSON_IsReference);
    CU_ASSERT_PTR_EQUAL(ref->valuestring, literal);

    // 删除应安全完成，不调用 free(literal)
    cJSON_Delete(ref); // 不崩溃即通过
}

// 测试 cJSON_Compare 的 case_sensitive 参数对对象键的影响
void test_cJSON_Compare_case_sensitive_object(void) {
    cJSON *obj1 = cJSON_Parse("{\"Name\":1}");
    cJSON *obj2 = cJSON_Parse("{\"name\":1}");
    CU_ASSERT_PTR_NOT_NULL(obj1);
    CU_ASSERT_PTR_NOT_NULL(obj2);

    // 不区分大小写：应相等
    CU_ASSERT_TRUE(cJSON_Compare(obj1, obj2, false));

    // 区分大小写：应不等
    CU_ASSERT_FALSE(cJSON_Compare(obj1, obj2, true));

    cJSON_Delete(obj1);
    cJSON_Delete(obj2);
}

// 测试 cJSON_Parse 失败后 cJSON_GetErrorPtr 返回正确位置
void test_cJSON_GetErrorPtr_on_parse_failure(void) {
    const char *invalid_json = "{\"a\":}";
    cJSON *root = cJSON_Parse(invalid_json);
    CU_ASSERT_PTR_NULL(root);

    const char *error_ptr = cJSON_GetErrorPtr();
    CU_ASSERT_PTR_NOT_NULL(error_ptr);
    // 错误应指向 '}' 前的位置，即 ':'
    CU_ASSERT_PTR_EQUAL(error_ptr, invalid_json + 5); // "{\"a\":}" -> error at ':'
}

// 测试 cJSON_ArrayForEach 宏的遍历行为（通过模拟其展开）
void test_cJSON_ArrayForEach_macro(void) {
    cJSON *arr = cJSON_Parse("[1, 2, 3]");
    CU_ASSERT_PTR_NOT_NULL(arr);
    CU_ASSERT_EQUAL(cJSON_GetArraySize(arr), 3);

    int count = 0;
    double sum = 0.0;
    cJSON *item = NULL;
    // 手动展开 cJSON_ArrayForEach(item, arr)
    for (item = arr->child; item != NULL; item = item->next) {
        count++;
        sum += cJSON_GetNumberValue(item);
    }
    CU_ASSERT_EQUAL(count, 3);
    CU_ASSERT_DOUBLE_EQUAL(sum, 6.0, 1e-9);

    cJSON_Delete(arr);
}

// 测试 cJSON_AddItemToObjectCS：使用常量字符串作为 key
void test_cJSON_AddItemToObjectCS_constant_key(void) {
    cJSON *obj = cJSON_CreateObject();
    const char *const_key = "const_key";
    cJSON *val = cJSON_CreateString("value");

    CU_ASSERT_TRUE(cJSON_AddItemToObjectCS(obj, const_key, val));
    cJSON *retrieved = cJSON_GetObjectItem(obj, "const_key");
    CU_ASSERT_PTR_NOT_NULL(retrieved);
    CU_ASSERT_STRING_EQUAL(cJSON_GetStringValue(retrieved), "value");
    // key 应直接指向 const_key
    CU_ASSERT_PTR_EQUAL(retrieved->string, const_key);
    CU_ASSERT_TRUE(retrieved->type & cJSON_StringIsConst);

    cJSON_Delete(obj);
}

// 测试 cJSON_Parse 支持注释（需先 Minify）
void test_cJSON_Parse_with_comments_via_Minify(void) {
    char json_with_comment[] = "{\n// comment\n\"a\": 1\n}";
    cJSON_Minify(json_with_comment);
    cJSON *obj = cJSON_Parse(json_with_comment);
    CU_ASSERT_PTR_NOT_NULL(obj);
    CU_ASSERT_TRUE(cJSON_IsObject(obj));
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetObjectItem(obj, "a")), 1.0, 1e-9);
    cJSON_Delete(obj);
}

// 测试 cJSON_CreateObjectReference 删除行为：不删除被引用的对象
void test_cJSON_CreateObjectReference_no_delete_referent(void) {
    cJSON *inner = cJSON_CreateObject();
    cJSON_AddNumberToObject(inner, "x", 42);

    cJSON *ref = cJSON_CreateObjectReference(inner);
    CU_ASSERT_PTR_NOT_NULL(ref);
    CU_ASSERT_TRUE(ref->type & cJSON_IsReference);
    CU_ASSERT_PTR_EQUAL(ref->child, inner);

    // 删除引用对象
    cJSON_Delete(ref); // 不应影响 inner

    // inner 仍可安全访问
    CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(cJSON_GetObjectItem(inner, "x")), 42.0, 1e-9);
    cJSON_Delete(inner);
}

// 测试 cJSON_CreateRaw 与打印行为：Raw 内容直接输出，不加引号
void test_cJSON_CreateRaw_print(void) {
    cJSON *raw = cJSON_CreateRaw("{\"inner\":1}");
    CU_ASSERT_PTR_NOT_NULL(raw);
    CU_ASSERT_TRUE(cJSON_IsRaw(raw));

    char *printed = cJSON_PrintUnformatted(raw);
    CU_ASSERT_PTR_NOT_NULL(printed);
    CU_ASSERT_STRING_EQUAL(printed, "{\"inner\":1}");
    cJSON_free(printed);
    cJSON_Delete(raw);
}

// 测试 cJSON_Duplicate 非递归模式（浅拷贝 child 不复制）
void test_cJSON_Duplicate_non_recursive(void) {
    cJSON *obj = cJSON_CreateObject();
    cJSON_AddNumberToObject(obj, "x", 10);
    CU_ASSERT_PTR_NOT_NULL(obj->child);

    cJSON *shallow = cJSON_Duplicate(obj, false);
    CU_ASSERT_PTR_NOT_NULL(shallow);
    CU_ASSERT_TRUE(cJSON_IsObject(shallow));
    CU_ASSERT_PTR_NULL(shallow->child); // non-recursive, child not copied

    cJSON_Delete(obj);
    cJSON_Delete(shallow);
}

// 测试 cJSON_ParseWithOpts 的 return_parse_end 参数
void test_cJSON_ParseWithOpts_return_parse_end(void) {
    const char *json_with_trailing = "{\"a\":1}  /* comment */ trailing";
    const char *end = NULL;
    cJSON *obj = cJSON_ParseWithOpts(json_with_trailing, &end, false);
    CU_ASSERT_PTR_NOT_NULL(obj);
    CU_ASSERT_PTR_NOT_NULL(end);
    // 解析应在 '}' 后停止（忽略后续空格/注释需 Minify，但默认不支持）
    // 实际上 cJSON 不跳过 trailing，所以 end 指向 '}'
    CU_ASSERT_EQUAL(end[-1], '}');
    cJSON_Delete(obj);
}

// 测试 cJSON_PrintPreallocated 缓冲区不足时返回 false
void test_cJSON_PrintPreallocated_buffer_too_small(void) {
    cJSON *obj = cJSON_Parse("{\"key\":\"value\"}");
    CU_ASSERT_PTR_NOT_NULL(obj);

    char small_buf[5] = {0};
    cJSON_bool result = cJSON_PrintPreallocated(obj, small_buf, sizeof(small_buf), false);
    CU_ASSERT_FALSE(result); // 缓冲区太小，应失败

    char large_buf[64] = {0};
    result = cJSON_PrintPreallocated(obj, large_buf, sizeof(large_buf), false);
    CU_ASSERT_TRUE(result);
    CU_ASSERT_PTR_NOT_NULL(strstr(large_buf, "key"));

    cJSON_Delete(obj);
}

// 测试 cJSON_Compare 对 NaN/Inf 数字的处理（cJSON 将其转为 null）
void test_cJSON_Compare_nan_inf_numbers(void) {
    cJSON *nan1 = cJSON_CreateNumber(NAN);
    cJSON *nan2 = cJSON_CreateNumber(NAN);
    // 注意：cJSON_Print 会将 NaN 输出为 "null"，但内部 type 仍是 cJSON_Number
    // 然而 cJSON_Compare 对 NaN 数字会因 valuedouble != 而返回 false
    CU_ASSERT_FALSE(cJSON_Compare(nan1, nan2, false));
    cJSON_Delete(nan1); cJSON_Delete(nan2);

    cJSON *inf1 = cJSON_CreateNumber(INFINITY);
    cJSON *inf2 = cJSON_CreateNumber(INFINITY);
    CU_ASSERT_FALSE(cJSON_Compare(inf1, inf2, false)); // 同理
    cJSON_Delete(inf1); cJSON_Delete(inf2);
}

// 测试 cJSON_GetArraySize 在深度嵌套对象中的正确性
void test_cJSON_GetArraySize_nested(void) {
    const char *json = "{\"a\":[1,2,{\"b\":[3,4]}]}";
    cJSON *root = cJSON_Parse(json);
    CU_ASSERT_PTR_NOT_NULL(root);

    cJSON *a = cJSON_GetObjectItem(root, "a");
    CU_ASSERT_EQUAL(cJSON_GetArraySize(a), 3);

    cJSON *inner_obj = cJSON_GetArrayItem(a, 2);
    cJSON *b = cJSON_GetObjectItem(inner_obj, "b");
    CU_ASSERT_EQUAL(cJSON_GetArraySize(b), 2);

    cJSON_Delete(root);
}

// 测试 cJSON_Delete 传入非法/循环结构的安全性（防御：cJSON 无 parent 指针，天然无循环）
void test_cJSON_Delete_safety_on_invalid_chains(void) {
    // 构造一个非法 next/prev 链（人为破坏）
    cJSON *a = cJSON_CreateNumber(1);
    cJSON *b = cJSON_CreateNumber(2);
    a->next = b;
    b->prev = a;
    // 但不设置 array 的 child，直接删 a（非标准用法，应不崩溃）
    cJSON_Delete(a); // b 会随链式删除被释放
    // 无断言，不崩溃即通过（CUnit 会捕获 segfault）
}

// 测试 cJSON_ArrayForEach 宏在各种数组长度下的展开行为（模拟使用）
void test_cJSON_ArrayForEach_macro_robustness(void) {
    // 空数组
    cJSON *arr = cJSON_CreateArray();
    int count = 0;
    cJSON *item;
    cJSON_ArrayForEach(item, arr) {
        (void)item;
        count++;
    }
    CU_ASSERT_EQUAL(count, 0);
    cJSON_Delete(arr);

    // 单元素
    arr = cJSON_Parse("[42]");
    count = 0;
    cJSON_ArrayForEach(item, arr) {
        CU_ASSERT_DOUBLE_EQUAL(cJSON_GetNumberValue(item), 42.0, 1e-9);
        count++;
    }
    CU_ASSERT_EQUAL(count, 1);
    cJSON_Delete(arr);

    // 多元素
    arr = cJSON_Parse("[1,2,3]");
    count = 0;
    double sum = 0;
    cJSON_ArrayForEach(item, arr) {
        sum += cJSON_GetNumberValue(item);
        count++;
    }
    CU_ASSERT_EQUAL(count, 3);
    CU_ASSERT_DOUBLE_EQUAL(sum, 6.0, 1e-9);
    cJSON_Delete(arr);
}